#!/usr/bin/env python

import ftplib, optparse, os, sys

def syntax(msg):
    p.error(msg)
    sys.exit(1)

def main(server, remote_file, local_file, user, passw):
  try:
    ftp = ftplib.FTP(server)
  except:
    sys.exit('\nError: Unable to connect to server - "%s"\n' % server)
  try:
    try:
        ftp.login(user, passw)	
    except ftplib.error_perm, msg:
	sys.exit('\nError: %s\n' % msg)
    try:
        outfile=open(local_file, 'wb')
    except IOError, msg:
	sys.exit("\nError: %s\n" % msg)
    try:
        if ftp.retrbinary('RETR ' + remote_file, outfile.write):
            return local_file
    except ftplib.error_perm, msg:
        if os.path.isfile(local_file):
            os.remove(local_file)
        sys.exit('\nError: %s\n' % msg)
  finally:
    ftp.close() 
     


if __name__=='__main__':

    	Usage='%prog  -s server -f filename [ -l localname | -u username | -p password ]'
	p=optparse.OptionParser(usage=Usage)
	p.add_option('--server', '-s', help='Hostname of the FTP server.', action="store", dest="server")
	p.add_option('--filename', '-f', help='Name of the file you want to download from the server.', action="store", dest="file")
	p.add_option('--localname', '-l', help='Name of the local file you are downloading from the server. Defaults to the same value as --filename', action="store", dest="localfile")
	p.add_option('--username', '-u', help='Username to connect with. Default is anonymous.', action="store", default="anonymous", dest="user")
	p.add_option('--password', '-p', help='Password to connect with.', action="store", default="")
	
	(options, args)=p.parse_args()
	
	if not options.server:
            syntax("You must pass at least --server and --filename args!\n")
	elif not options.file:
            syntax("You must pass at least --server and --filename args!\n")
	elif not options.localfile:
	    options.localfile=os.path.basename(options.file)
        
	main(options.server, options.file, options.localfile, options.user, options.password)
 
